from fastapi import APIRouter,Depends
from sqlalchemy.orm import Session
from sqlalchemy import desc
from loguru import logger
from db.mysql import get_db
from vendor.extend.courier import *
from model.ground_sensor import GroundSensor as SensorTable,FormBody,EditBody
from model.ground_mine import GroundMine
from vendor.extend.conversion import is_3x3_matrix_of_numbers,is_6_by_9_grid
from vendor.extend.conversion import is_positive_integer

GroundSensor = APIRouter()

@GroundSensor.post('/add')
async def add_sensor(itme:FormBody,db: Session = Depends(get_db)):
    item = itme.dict()
    mine = db.query(GroundMine.id,GroundMine.colliery_id).filter_by(id=item.get('mine_id',0)).first()
    if not mine:
        return Error(msg='钻孔不存在')
    transformation_matrix=list(item.get('transformation_matrix',[]))
    stress_matrix=list(item.get('stress_matrix',[]))
    if not is_3x3_matrix_of_numbers(transformation_matrix):
        return Error(msg='传感器坐标转换矩阵为3*3的数字矩阵')

    if not is_6_by_9_grid(stress_matrix):
        return Error(msg='传感器坐标转换矩阵为6*9的数字矩阵')

    add_data=SensorTable(
        mine_id=mine.id,
        colliery_id=mine.colliery_id,
        sensor_number=item.get('sensor_number',''),
        chanel=item.get('chanel',''),
        setup_time=item.get('setup_time',0),
        sensor_status=item.get('sensor_status',''),
        coefficient=item.get('coefficient',0),
        stress_matrix=stress_matrix,
        transformation_matrix=transformation_matrix,
        wavelength=item.get('wavelength',0),
        create_time=int(time.time())
    )

    try:
        # 执行一些数据库操作
        db.add(add_data)
        db.flush()
        db.commit()
        db.refresh(add_data)
    except Exception as e:
        # 手动回滚会话并重新抛出异常
        db.rollback()
        logger.error("传感器 添加 出错:{}", e)
        return Error(msg="传感器添加失败",data=str(e))

    return Success(msg='传感器添加成功',data={'sensor_id':add_data.id,'create_time':add_data.create_time})



@GroundSensor.post('/edit')
async def edit_sensor(item:EditBody,db: Session = Depends(get_db)):
    item_dict = item.dict()
    transformation_matrix=list(item_dict.get('transformation_matrix',[]))
    stress_matrix=list(item_dict.get('stress_matrix',[]))
    if not is_3x3_matrix_of_numbers(transformation_matrix):
        return Error(msg='传感器坐标转换矩阵为3*3的数字矩阵')

    if not is_6_by_9_grid(stress_matrix):
        return Error(msg='传感器坐标转换矩阵为6*9的数字矩阵')
    edit_data={
        'sensor_number':item_dict.get('sensor_number',''),
        'chanel':item_dict.get('chanel',''),
        'setup_time':item_dict.get('setup_time',0),
        'sensor_status':item_dict.get('sensor_status',''),
        'coefficient':item_dict.get('coefficient',0),
        'stress_matrix':stress_matrix,
        'transformation_matrix':transformation_matrix,
        'wavelength':item_dict.get('wavelength',0),
        'update_time':int(time.time())
    }

    try:
        # 执行一些数据库操作
        db.query(SensorTable).filter_by(id=item_dict.get('sensor_id',0)).update(edit_data)
        db.commit()
    except Exception as e:
        # 手动回滚会话并重新抛出异常
        db.rollback()
        logger.error("传感器信息 更新 出错:{}", e)
        return Error(msg='传感器更新错误',data=str(e))


    return Success(msg='更新成功',data=edit_data)


@GroundSensor.get('/getlist')
async def colliery_list(mine_id:int=0,db: Session = Depends(get_db)):
    if not is_positive_integer(mine_id):
        return Error(msg='钻孔ID参数错误')

    data_list=db.query(SensorTable).filter_by(mine_id=mine_id).order_by(SensorTable.id.desc()).all()
    list_data=[]
    for info in data_list:
        list_data.append({
            "id":info.id,
            "mine_id":info.mine_id,
            "colliery_id":info.colliery_id,
            "sensor_number":info.sensor_number,
            "chanel":info.chanel,
            "setup_time":info.setup_time,
            "sensor_status":info.sensor_status,
            "coefficient":info.coefficient,
            "stress_matrix":info.stress_matrix,
            "transformation_matrix":info.transformation_matrix,
            "wavelength":info.wavelength,
            "create_time":info.create_time
        })
    return Success(msg='传感器列表',data=list_data)